package com.fc.converters;

import javax.faces.bean.ApplicationScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.fc.entities.MeasurementType;
import com.fc.service.MeasurementTypeService;
import com.fc.utils.ServiceLocator;

/**
 * 
 * @author aacs
 * 
 */
@Component("measurementTypeConverter")
@ApplicationScoped
public class MeasurementTypeConverter implements Converter {
	private MeasurementTypeService service;

	public MeasurementTypeService getService() {
		if (service == null) {
			service = ServiceLocator.getBean(MeasurementTypeService.class);	
		}
		return service;
	}

	@Override
	public MeasurementType getAsObject(FacesContext context, UIComponent component, String value) {
		if (StringUtils.isBlank(value)) {
			return null;
		}

		return getService().findByName(value);
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if (value == null || !(value instanceof MeasurementType)) {
			return "";
		}
		MeasurementType entity = (MeasurementType) value;
		return entity.getName();
	}
}
